import Vue from 'vue'
import Vuex from 'vuex'
import _ from 'lodash'
import { formatStyle } from '@/utils/style'
import bus from '@/utils/eventBus.js'
import { Message } from 'element-ui'
import { calculateStyle, resetComponentStyle, recoverComponentStyle } from '@/utils/calculate.js'
Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		componentData: JSON.parse(window.localStorage.getItem('componentData')) || [],
		curComponent: null,
		curComponentList: [],
		curIndex: -1,
		// 状态栈
		stack: [],
		// 当前状态指针
		p: -1,
		isPreview: {
			data: false
		},
		canvasStyleData: {
			// 页面全局数据
			width: 1200,
			height: 740,
			color: '#000',
			opacity: 1,
			backgroundColor: '#fff',
			fontSize: 14
		},
		menuShow: false,
		menuStyleData: {
			top: 0,
			left: 0
		},
		copyData: null,
		isScreenshot: false
	},
	getters: {
		// 用于展示正在画布中的组件层级
		reverseData(state) {
			return state.componentData.slice().reverse()
		},
		// 格式化画布样式数据
		formatCanvasStyle(state) {
			const result = {}
			Object.keys(state.canvasStyleData).forEach((key) => {
				result[key] = state.canvasStyleData[key]
				if (key === 'fontSize' || key === 'width' || key === 'height') {
					result[key] += 'px'
				}
			})

			return result
		},
	},
	mutations: {
		// 添加画布中的组件
		addComponent(state, option) {
			state.componentData.push(option)
		},
		// 修改组件间的层级
		swapComponent(state, tuple = []) {
			let i = tuple[0]
			let j = tuple[1]
			let componentI = state.componentData[i]
			let componentJ = state.componentData[j]
			Vue.set(state.componentData, i, componentJ)
			Vue.set(state.componentData, j, componentI)
		},
		topComponent(state, index) {
			let component = state.componentData[index]
			state.componentData.splice(index, 1)
			state.componentData.push(component)
		},
		bottomComponent(state, index) {
			let component = state.componentData[index]
			state.componentData.splice(index, 1)
			state.componentData.unshift(component)
		},
		// 删除画布中的组件
		removeComponent(state, index) {
			state.componentData.splice(index, 1)
			store.commit('saveHistoryState')
		},
		// 设置当前选中的组件
		setCurComponent(state, component) {
			// component.isCurrent = true
			state.curComponent = component
			store.commit('resetCurrent')
		},
		// 重置选中状态
		resetCurrent(state) {
			state.componentData.forEach((item) => {
				if (item.isCurrent == true) {
					item.isCurrent = false
				}
			})
			if (state.curComponent != null) {
				state.curComponent.isCurrent = true
			}
		},
		// 获取当前组件的索引
		getIndex(state) {
			if (state.curComponent == null) {
				state.$message.error("请选择组件");
				state.curIndex = -1
				return
			}
			let index = state.componentData.findIndex(
				(item) => item.id == state.curComponent.id
			);
			state.curIndex = index
		},
		// 修改画布样式
		setCanvasStyle(state, style) {
			state.canvasStyleData = style
		},
		// 修改选中控件的样式
		setCurComponentStyle(state, style) {
			state.curComponent.style = style
		},
		// 修改选中的私有属性
		editorPropValue(state, val) {
			state.curComponent.propValue = val
		},
		// 保存历史状态
		saveHistoryState(state) {
			state.p++
			// p之后的记录删除
			state.stack = state.stack.slice(0, state.p)
			let history = JSON.stringify(state.componentData)
			state.stack.push(history)
		},
		// 指针后退
		backP(state) {
			if (state.p <= 0) return Message.info('已是最初始状态');
			state.p--
			let nowState = state.stack[state.p]
			store.commit('resetData', JSON.parse(nowState))
		},
		// 指针前进
		forwardP(state) {
			if (state.p >= state.stack.length - 1)
				return Message.info('已是最新状态');
			state.p++
			let nowState = state.stack[state.p]
			store.commit('resetData', JSON.parse(nowState))
		},
		// 重置componentData和curComponent
		resetData(state, data) {
			state.componentData = data
			if (state.curComponent != null) {
				let res = state.componentData.some((item) => {
					if (item.id == state.curComponent.id) {
						// 使curComponent和item指向同一份地址
						state.curComponent = item
						return true
					}
				})
				// 如果选中元素已经被删除
				if (!res) state.curComponent = null
			}
			store.commit('resetCurrent')
		},

		// 设置预览窗口
		setPreview(state, boolean) {
			state.isPreview.data = boolean
		},
		setScreenShot(state, boolean) {
			state.isScreenshot = boolean
		},
		// 保存数据
		saveData(state) {
			window.localStorage.setItem('componentData', JSON.stringify(state.componentData))
			Message.success('保存成功')
		},
		// 设置锁定状态
		setLock(state, flag) {
			state.curComponent.islock = flag
		},

		// 显示右击菜单
		showContextMenu(state, position) {
			state.menuShow = true
			state.menuStyleData = position
		},
		// 隐藏右击菜单
		hideContextMenu(state) {
			state.menuShow = false
		},
		// 复制
		copy(state) {
			if (state.curComponent == null) return Message.error('请选择组件')
			state.copyData = state.curComponent
		},
		// 粘贴
		paste(state) {
			if (state.copyData == null) return Message.error('请选择组件');
			state.copyData = _.cloneDeep(state.copyData)
			state.copyData.style = formatStyle({ ...state.copyData.style, ...state.menuStyleData })
			bus.$emit('paste', state.copyData)
		},
		// 删除
		delete(state) {
			store.commit('getIndex');
			let index = state.curIndex;
			if (index == -1) return;
			store.commit('removeComponent', index);
		},
		// 剪切
		cut() {
			store.commit('copy');
			store.commit('delete');
		},
		// 添加事件
		addEvent(state, event) {
			let { type, cb } = event;
			state.curComponent.events[type] = cb
		},
		// 添加选中组件
		addCurComponent(state, id) {
			if (state.curComponentList.includes(id)) return
			state.curComponentList.push(id);
		},
		// 清空选中的所有组件
		clearcurComponentList(state) {
			state.componentData.forEach(item => {
				item.isCompose = false
			})
			state.curComponentList = [];
		},
		// 组合
		compose(state) {
			let newData = [];
			let composeData = [];
			state.componentData.forEach(item => {
				if (item.isCompose) {
					composeData.push(item)
				} else {
					newData.push(item)
				}
			})
			state.componentData = newData;
			let style = calculateStyle(composeData)
			resetComponentStyle(composeData, style.left, style.top);
			let component = {
				component: 'Group',
				label: '组合',
				propValue: composeData,
				icon: 'help',
				isCurrent: false,
				isCompose: false,
				islock: false,
				request: {},
				style: formatStyle(style),
				events: {
				}
			};
			bus.$emit('paste', component)
		},
		// 拆分
		split(state) {
			let id = state.curComponent.id;
			let index = state.componentData.findIndex(item => item.id == id);
			let groupComponent = state.componentData[index];
			let position = groupComponent.position;
			state.componentData.splice(index, 1);
			recoverComponentStyle(groupComponent.propValue, position.left, position.top)
			groupComponent.propValue.forEach(item => {
				state.componentData.push(item);
			})
			state.curComponent = null;
			store.commit('resetCurrent');
			store.commit('clearcurComponentList');
		},
	},
	actions: {},
	modules: {}
})

export default store
